package com.topnav.mc.admin.controller;

import com.js.lib.result.Result;
import com.js.lib.utils.DateUtils;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DevicePosition;
import com.topnav.mc.admin.entity.DevicePositionTemp;
import com.topnav.mc.admin.entity.wrapper.DevicePositionTempWrapper;
import com.topnav.mc.admin.service.IDevicePositionService;
import com.topnav.mc.admin.service.IDevicePositionTempService;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.base.mc.McController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value = "admin/device/pos/temp", tags = "临时定位数据")
@RestController
@CrossOrigin
@RequestMapping("admin/device/pos/temp")
public class DevicePositionTempController extends McController<DevicePositionTemp, DevicePositionTemp, DevicePositionTemp, IDevicePositionTempService, DevicePositionTempWrapper> {

    @Autowired
    private IDevicePositionTempService devicePositionTempService;
    @Autowired
    private IDevicePositionService devicePositionService;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 定位信息从临时表写正式表
     **/
    @PostMapping("/trans/to/test")
    @ResponseBody
    public Result transFromTemp(Long deviceId, String beginTime) {
        if (deviceId==null){
            return Result.error("参数deviceId必须提供");
        }
        if (StringUtils.isEmpty(beginTime)){
            return Result.error("参数beginTime必须提供");
        }

        Device device = deviceService.getById(deviceId);
        if (device==null){
            return Result.error(String.format("不存在的设备ID %s",deviceId));
        }

        Date time = DateUtils.parseDateTime(beginTime);
        List<DevicePosition> batch = new ArrayList<>();
        List<DevicePositionTemp> list = devicePositionTempService.listInfo();
        for(DevicePositionTemp pos : list){
            DevicePosition devicePosition = new DevicePosition();
            devicePosition.setDeviceId(deviceId);
            devicePosition.setDeviceCode(device.getCode());
            devicePosition.setDeviceName(device.getName());
            time = new Date(time.getTime()+30*1000);
            devicePosition.setTime(time);
            devicePosition.setLongitude(pos.getLongitude());
            devicePosition.setLatitude(pos.getLatitude());
            devicePosition.setCreateTime(new Date());
            batch.add(devicePosition);
            if (batch.size() >= 50){
                devicePositionService.saveBatch(batch,batch.size());
                batch.clear();
            }

        }
        if (batch.size() >= 50){
            devicePositionService.saveBatch(batch,batch.size());
            batch.clear();
        }

        return Result.ok();


    }

}
